<?php

class DocumentService extends \BaseService {

    /**
     * 获取内容列表
     * @param  [id] $id [栏目id]
     * @return [array] [栏目id、栏目名、文档内容]
     */
    public static function index($id){
        $category = Category::find($id);
        if(!isset($category)){
            throw new CategoryNoFoundException;
        }

        $modelId = $category['model_id'];
        $tableName = Model::where('id', $modelId)->pluck('table_name');
        $tableName = studly_case($tableName);
        if(!isset($tableName)){
            throw new ModelNoFoundException;
        }

        $document  new $tableName;
        $documents = $document::all();
        // $documents = DB::table($tableName)->get();
        $documents = array('category' => $category, 'documents' => $documents);
        return $documents;
    }

    /**
     *  进入文档增加页面
     * @param  [int] $id [栏目id]
     * @return [array] [栏目信息，模板字段信息]
     */
    public static function create($id){

        $category = Category::find($id);
        if(!isset($category)){
            return new CategoryNoFoundException;
        }

        $modelId = $category['model_id'];
        $fields = Field::where('model_id', $modelId)->get();
        if(!isset($fields)){
            return new FieldNoFoundException;
        }

        // $document = array('category' => $category, 'fields' => $fields);
        $document = <<<Eof
    <form action="/cms/document/add" method="post">
        <input type="hidden" name="id" value=$id />
        <table>
Eof;
        foreach($fields as $field){
            if($field['type']=='text'){
                $document.=<<<Eof
                <tr>
                    <td>
                        {$field['display_name']}
                    </td>
                    <td>
                    <textarea name={$field['name']} ></textarea>
                    </td>
                </tr>
Eof;
            }else{
                $document.=<<<Eof
                <tr>
                    <td>
                        {$field['display_name']}
                    </td>
                    <td>
                    <input type="text" name={$field['name']} />
                    </td>
                </tr>
Eof;
            }
        }
        $document.=<<<Eof
        <tr>
                <td></td>
                <td><input type="submit" value="add"/></td>
            </tr>
        </table>
    </form>
Eof;
        return $document;
    }

    /**
     * 增加文档
     * @param [idt] $id [栏目id]
     */
    public static function add($id, $inputParam){
        try{
            DB::transaction(function() use ($id, $inputParam){
                $modelId = Category::where('id', $id)->pluck('model_id');
                if(!isset($modelId)){
                    throw new CategoryNoFoundException;
                }
                $model = Model::find($modelId);
                if(!isset($model)){
                    throw new ModelNoFoundException;
                }
                $tableName = $model['table_name'];
                $fields = Field::where('model_id', $modelId)->get();
                
                //增加文档
                $model = new $tableName;
                //判断字段是否属于该模型
                foreach ($inputParam as $key => $value) {
                    $model->category_id = $id;
                    //判断字段类型是否与模型字段类型符合
                    foreach ($fields as $number => $field) {

                        if($key==$field['name']){
                            
                            //数据类型为string
                            if($field['type']=='string'){
                                if(is_string($value)){
                                    if(strlen($value)>255){
                                        throw new Exception('字符串长度超过255',10000);
                                    }
                                    $model->$key=$value;
                                }
                            }
                            
                            //数据类型为integer
                            if($field['type']=='integer'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'integer')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为boolean
                            if($field['type']=='boolean'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'boolean')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为date
                            if($field['type']=='date'){
                                if(date('Y-m-d', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }
                            
                            //数据类型为dateTime,timestamp
                            if($field['type']=='dateTime' || $field['type']=='timestamp'){
                                if(date('Y-m-d H:i:s', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }

                            //time
                            if($field['type']=='time'){
                                if(date('H:i:s', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }
                            
                            //数据类型为数字
                            if($field['type']=='double' || $field['type']=='decimal'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'numeric')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为text,longText
                            if($field['type']=='text' || $field['type']=='longText'){
                                if(is_string($value)){
                                    $model->$key=$value;
                                }
                            }
                        }
                        $model->save();
                    }
                }
            });
        }catch(Exception $e){
            throw new DocumentAddException;
        }
        return self::getResult('成功添加文档');

    }

    /**
     * 进入文档更改页面
     * @param  [int] $id         [文档id]
     * @param  [int] $categoryId [栏目id]
     * @return [array]             [文档信息，模板字段]
     */
    public static function show($id, $categoryId){
        $modelId = Category::where('id', $categoryId)->pluck('model_id');
        if(!isset($modelId)){
            throw new CategoryNoFoundException;
        }
        $tableName = Model::where('id', $modelId)->pluck('table_name');

        $model = new $tableName;
        $documents = $model::find($id);
        if(!isset($documents)){
            throw new DocumentNoFoundException;
        }
        $fields = Field::where('model_id', $modelId)->lists('name');
        if(!isset($fields)){
            throw new FieldNoFoundException;
        }
        $documents = array('documents' => $documents, 'fields' => $fields);
        return $documents;
    }

    /**
     * 更新文档数据
     * @param  [int] $id         [文档id]
     * @param  [int] $categoryId [栏目id]
     */
    public static function update($data){
        try{
            DB::transaction(function() use ($data){
                $modelId = Category::where('id', $data['categoryId'])->pluck('model_id');
                if(!isset($modelId)){
                    throw new CategoryNoFoundException;
                }
                $model = Model::find($modelId);
                if(!isset($model)){
                    throw new ModelNoFoundException;
                }
                $tableName = $model['table_name'];
                $fields = Field::where('model_id', $modelId)->get();
                if(!isset($fields)){
                    throw new FieldNoFoundException;
                }
                $model = $tableName::where('id', $data['id'])->first();
                if(!isset($model)){
                    throw new ModelNoFoundException;
                }
                //判断字段是否属于该模型
                foreach ($data as $key => $value) {
                    $model->category_id = $data['categoryId'];
                    //判断字段类型是否与模型字段类型符合
                    foreach ($fields as $number => $field) {
                        if($key==$field['name']){
                            
                            //数据类型为string
                            if($field['type']=='string'){
                                if(is_string($value)){
                                    if(strlen($value)>255){
                                        throw new Exception('字符串长度超过255',10000);
                                    }
                                    $model->$key=$value;
                                }
                            }
                            
                            //数据类型为integer
                            if($field['type']=='integer'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'integer')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为boolean
                            if($field['type']=='boolean'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'boolean')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为date
                            if($field['type']=='date'){
                                if(date('Y-m-d', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }
                            
                            //数据类型为dateTime,timestamp
                            if($field['type']=='dateTime' || $field['type']=='timestamp'){
                                if(date('Y-m-d H:i:s', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }

                            //time
                            if($field['type']=='time'){
                                if(date('H:i:s', strtotime($value)) === $value){
                                    $model->$key=$value;
                                }
                                throw new Exception('时间错误');
                            }
                            
                            //数据类型为数字
                            if($field['type']=='double' || $field['type']=='decimal'){
                                self::validateInput(
                                            array('value' => $value),
                                            array('value' => 'numeric')
                                        );
                                $model->$key=$value;
                            }
                            
                            //数据类型为text,longText
                            if($field['type']=='text' || $field['type']=='longText'){
                                if(is_string($value)){
                                    $model->$key=$value;
                                }
                            }
                        }
                        $model->save();
                    }
                }
            });
        }catch(Exception $e){
            throw new DocumentUpdateException;
        }
        return self::getResult('成功更新文档');
    }

    /**
     * 删除文档
     * @param  [int] $id         [文档id]
     * @param  [int] $categoryId [栏目id]
     */
    public static function delete($data){
        try{
            $modelId = Category::where('id', $data['categoryId'])->pluck('model_id');
            if(!isset($modelId)){
                throw new CategoryNoFoundException;
            }
            $model = Model::find($modelId);
            if(!isset($model)){
                throw new ModelNoFoundException;
            }
            $modelName = ucfirst($model['table_name']);
            $model = $modelName::where('id', $data['id'])->first();
            if(!isset($model)){
                throw new ModelNoFoundException;
            }
            $model->delete();
        }catch (Exception $e){
            throw new DocumentDeleteException;
        }
        return self::getResult('成功删除文档');
    }

}